/**
 * Created by Dalyn on 2017/2/28.
 */
import React from "react";
import { hashHistory,Link } from 'react-router';
import Confirm from '../../common/Confirm'
import Relay from "react-relay";
import {Table,message,Menu, Dropdown, Icon,Upload,InputNumber,Select,Tooltip } from 'antd';
import {Modal,Button,Input} from 'fly';

const Option = Select.Option;
import ListOrderMutation from "./mutation/ListOrderMutation";
import FinishOrderMutation from "./mutation/FinishOrderMutation";
import RelevanceTraffickerMutation from "./mutation/RelevanceTraffickerMutation";
import GetEnterpriseListMutation from "./mutation/GetEnterpriseListMutation";
import FindUsersByEnterpriseIdAndPidMutation from "./mutation/FindUsersByEnterpriseIdAndPidMutation";
import findSampleCreateByOrderId from './mutation/findSampleCreateByOrderId';

import InfoOrder from './mutation/InfoOrder';  // 获得发货详情信息,

import GetQiNiuToken from './mutation/GetQiNiuTokenMutation';// 获取上传图片touken

import SendGoodsOrderMutation from './mutation/SendGoodsOrderMutation';  //发货

import DelQiniuFileMutation from './mutation/DelQiniuFileMutation';


import Order_Item from './Order_Item'
import './css/IndentManage.css'
import Util from "../../util/Util"
import Pagination from "./Pagination"
import Reactkey from "../../util/ReactKey"
import "./css/ListOrder_SaleAndRe.css";
import InputBox from "../../common/InputBox";
import Config from "../../util/Config"

/*信息列表*/
export default class ListOrder extends React.Component{
    constructor(props){
        super(props);
        this.state={
            orders:[],
            totalresult:0,
            placeholder:'请输入企业名称进行搜索',
            loading:true,
            outDetailModalInfo:{},  // 发货table数据
            relationModalFlag:false,
            enterpriseList:[],
            linkman:[],
            relationOid:"",
            relationEnterpriseId:"",
            relationPartAUserId:"",
            tradeKey:"ok",
            linkKey:"",
        };
        this.odtail='1';
        this.ods='';
        this.enid = sessionStorage.getItem('enterpriseId');
        this.serviceType = sessionStorage.getItem('serviceType');
        this.odsobj={'-1':'待创建',0:'待发布',1:'待接单',2:'待签订',3:'已签订',4:'交易完成'};
        this.goodtypeobj={'1':'成衣','2':'辅料','3':'面料','4':'印染','5':'纱线'}
        this.enterpriseList=[];
        this.linkman=[];
        this.inoutHttpRequest = this.inoutHttpRequest.bind(this);
        this.messageFlag = true;
    }


    componentWillMount(){
        this.queryorderlist(10,1);
    }

    componentDidMount(){

    }

    queryorderlist(pageSize,pageNum){
        let enName = this.refs.enName ? this.refs.enName.state.text : '';
        let styleNo = this.refs.styleNo ? this.refs.styleNo.state.text : '';
        let orderType = '';
        if(this.serviceType ==1){
            orderType = '1'
        }else if(this.serviceType ==2){
            orderType = '2'
        }else if(this.serviceType ==3){
            orderType = '3'
        }else if(this.serviceType ==4){
            orderType = '4'
        }else if(this.serviceType ==5){
            orderType = '5'
        }else if(this.serviceType ==6){
        }

        Relay.Store.commitUpdate(
            new ListOrderMutation({
                pageSize: pageSize,
                pageNum: pageNum,
                status:'3,4',
                type:this.odtail,
                enId:this.enid,
                enName:enName||'',
                styleNo:styleNo || '',
                searchType:1,
                // orderType:orderType
            }),
            {
                onFailure: () => {
                    message.error('请求失败');
                    this.setState({
                        loading:false,
                    })
                },
                onSuccess: (response) => {
                    let errorCode = response.listOrder.listOrder.errorCode;
                    if(errorCode=='0'){
                        let orders = response.listOrder.listOrder.orders
                        let totalResult = response.listOrder.listOrder.totalResult
                        this.setState({
                            orders:orders,
                            totalresult:totalResult,
                            loading:false,
                        });
                    }else {
                        this.setState({
                            loading:false,
                        });
                        if(errorCode==500){
                            message.error("服务器错误，请联系系统管理员");
                        }
                    }
                }
            }
        )
    }

    sendgoods(status,oid,partb,type){
        if(status!=3){
            return
        }
        hashHistory.push('/sendGoods/'+oid)

    }

    jumpGoodsRecord(oid){
        hashHistory.push('/sendGoodsRecord/'+oid)
    }


    jumpDetil(oty,oid){
        switch (oty){
            case 0:

                return;
            case 1:
                hashHistory.push('/orderdetailgms/'+oid);
                // hashHistory.push({pathname:'/orderdetailgms/',state:{'oid':oid}})
                return;
            case 2:
                hashHistory.push('/orderdetailraw/'+oid);
                // hashHistory.push({pathname:'/orderdetailraw/',state:{'oid':oid}})
                return;
            case 3:
                hashHistory.push('/orderdetailcloth/'+oid);
                // hashHistory.push({pathname:'/orderdetailcloth/',state:{'oid':oid}})
                return;
            case 4:
                hashHistory.push('/orderdetailprint/'+oid);
                // hashHistory.push({pathname:'/orderdetailprint/',state:{'oid':oid}})
                return;
            case 5:
                hashHistory.push('/orderdetailyarn/'+oid);
                // hashHistory.push({pathname:'/orderdetailprint/',state:{'oid':oid}})
                return;

        }
    }
    jumptree(oid){
        hashHistory.push({pathname:'/ordertree/',state:{'oid':oid}})
    }

    addDepartmenlist(){
        return this.state.orders.map((context,index)=>{
            return (
                <thead key={index+'-'}>
                <tr className={index%2==0?"order_list_saleandre_from_trchange":"order_list_saleandre_from_tr"}>
                    <td className="order_list_saleandre_from_td order_list_saleandre_from_td_oid_context" onClick={this.jumptree.bind(this,context.oid)}> {context.oid}</td>
                    <td className="order_list_saleandre_from_td order_list_saleandre_from_td_partb">{context.partAName}</td>
                    <td className="order_list_saleandre_from_td order_list_saleandre_from_td_product">{this.goodtypeobj[context.orderType]}</td>
                    <td className="order_list_saleandre_from_td order_list_saleandre_from_td_count">{Number(context.orderGoodsNum).toFixed(3)}</td>
                    <td className="order_list_saleandre_from_td order_list_saleandre_from_td_money">{context.account/100}</td>
                    <td className="order_list_saleandre_from_td order_list_saleandre_from_td_money">{context.payAccount/100}</td>
                    <td className="order_list_saleandre_from_td order_list_saleandre_from_td_doitcontext" onClick={this.sendgoods.bind(this,context.status,context.oid,context.partB,context.orderType)}>{
                        context.status==3?
                            <div className="order_list_saleandre_from_td_doitcontext_div">{'发货'}</div>
                            :
                            '交易完成'
                    }</td>
                    <td className="order_list_saleandre_from_td order_list_saleandre_from_td_endcontext" onClick={this.jumpGoodsRecord.bind(this,context.oid)}>查看</td>
                    <td className="order_list_saleandre_from_td order_list_saleandre_from_td_endcontext"><Link to = {{pathname:"OrderProgress", query:{oid: context.oid}}}>查看</Link></td>
                    <td className="order_list_saleandre_from_td order_list_saleandre_from_td_endcontext" onClick={this.jumpDetil.bind(this,context.orderType,context.oid)}>查看</td>
                </tr>
                </thead>
            );
        });
    }

    stroke(){

    }

    status(){
        return this.oArr.map((item,index)=>{
            return (
                <span style={{width:80,height:27,borderRadius:"8px",background:"#ccc",display:"block"}} onClick={this.stroke.bind(this)}>{item}</span>
            )
        })
    }

    createorder(){
        hashHistory.push('/createorder')
    }

    onSure(size,num){
        this.setState({
            loading:true,
        },this.queryorderlist(size,num))
    }

    onfocusInput(){
        this.setState({
            placeholder:''
        })
    }


    bluronInput(){
        // this.setState({
        //     placeholder:'请输入企业名称进行搜索'
        // })
    }

    _SearchByEn(){
        this.queryorderlist(10,1);
        this.refs.pagination.setState({
            text:1
        })
    }
    /*跳转到上下游订单关系*/
    jumpstreamshow(oid){
        hashHistory.push({pathname:'/orderstreamshow/',state:{'oid':oid}})
    }

    inoutHttpRequest(orderId,callback){
        Relay.Store.commitUpdate(
            new InfoOrder({
                orderId:orderId,
                enId:sessionStorage.getItem('enterpriseId')
            }),{
                onFailure:(err)=>{
                    message.error("网络连接失败，请联系系统管理员");
                },
                onSuccess:(res)=>{
                    const d = JSON.parse(JSON.stringify(res.infoOrder.infoOrder));
                    let or = d.order.orderGoodss;

                    //asdasd
                    if(d.errorCode == "0"){

                        // 整理数据格式  [ 时间，剩余数量，以及空换"-" ]
                        or.forEach((item,index)=>{
                            if(item.quantity && item.sendQuantity){
                                item.remainingQuantity = item.quantity - item.sendQuantity;
                            }else if(!item.sendQuantity){
                                // 无值就是总数量
                                item.remainingQuantity = item.quantity;
                            }
                            item.goodsId = item.gid;
                            delete item.gid;

                            item.productName = item.productName || "-";
                        });
                        callback && callback(or)
                    }else{
                        if(d.errorCode == "500"){ message.error("服务器错误，请联系系统管理员"); }else {
                            message.info("网络错误，请刷新页面或重试");
                        }
                    }
                }
            }
        )
    }
    /*完成交易*/
    _DealFinished(oid){
        Relay.Store.commitUpdate(
            new FinishOrderMutation({
                orderId:oid,
            }),
            {
                onFailure: () => {
                    message.info('请求失败');
                },
                onSuccess: (response) => {
                    let errorCode = response.finishOrder.finishOrder.errorCode;
                    let value  = response.finishOrder.finishOrder.value;
                    if(errorCode==0){
                        let _pageNum = this.refs.pagination.state.text;
                        this.queryorderlist(10, _pageNum);
                        this.setState({
                            visible:false
                        }, message.success('交易完成'));
                    }else{
                        message.info('交易金额不符，请填写合同补充');
                    }
                }
            }
        )

    }
    /*关联贸易商modal*/
    handleOk(){
        let {relationOid,relationEnterpriseId,relationPartAUserId} = this.state;
        if(!relationEnterpriseId){
            let this_ = this;
            Util.messageHint(this_,"info","请选择贸易商")
            return
        }
        if(!relationPartAUserId){
            let this_ = this;
            Util.messageHint(this_,"info","请选择联系人")
            return
        }
        Relay.Store.commitUpdate(
            new RelevanceTraffickerMutation({
                oid:relationOid,
                partA:relationEnterpriseId,
                partAUserId:relationPartAUserId,
            }),
            {
                onFailure: () => {
                    message.error("请求失败")
                },
                onSuccess: (response) => {
                    let errorCode = response.relevanceTrafficker.relevanceTrafficker.errorCode;
                    if(errorCode == 0){
                        this.setState({
                            relationEnterpriseId:"",
                            relationPartAUserId:"",
                            relationModalFlag:false,
                            tradeKey:Reactkey.key,
                            linkKey:Reactkey.key,
                            enterpriseList:[],
                            linkman:[],
                        },()=>{
                            let pageNum = this.refs.pagination.state.text;
                            this.queryorderlist(10,pageNum);
                            message.info("关联成功")
                        });
                    }
                }
            }
        )
    }
    handleCancel(){
        this.setState({
            relationEnterpriseId:"",
            relationPartAUserId:"",
            relationModalFlag:false,
            tradeKey:Reactkey.key,
            linkKey:Reactkey.key,
            enterpriseList:[],
            linkman:[],
        });
    }
    /*选择贸易商*/
    selectChange(id){
        this.setState({
            relationEnterpriseId:id,
            relationPartAUserId:"",
        });
        Relay.Store.commitUpdate(
            new FindUsersByEnterpriseIdAndPidMutation({
                enterpriseId : id,
                /*销售订单管理权限的用户*/
                pid:'11'
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {
                    let errorCode = response.findUsersByEnterpriseIdAndPid.findUsersByEnterpriseIdAndPid.errorCode;
                    if(errorCode=="0"){
                        let userModelList = response.findUsersByEnterpriseIdAndPid.findUsersByEnterpriseIdAndPid.userModelList;
                        let linkmanSelf=[];
                        userModelList.map((context,index)=>{
                            linkmanSelf.push({
                                text:context.name+" "+context.phone,
                                uid:context.uid,
                                name:context.name,
                                phone:context.phone,
                            })
                        });
                        this.setState({
                            linkman:linkmanSelf,
                            linkKey:userModelList?userModelList[userModelList.length-1].uid:"0000"
                        });
                    }
                }
            }
        )
    }
    /*文本变化回调*/
    selectSearch(value){
        Relay.Store.commitUpdate(
            new GetEnterpriseListMutation({
                serviceType: 6,
                enterpriseName:value,
                // pageSize: 5,
                // pageNum: 1,
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {
                    let errorCode = response.getEnterpriseList.data.errorCode;
                    if(errorCode == 0){
                        let enterpriseList = response.getEnterpriseList.data.enterpriseList;
                        let enterpriseListSelf = [];
                        enterpriseList.map((context,index)=>{
                            enterpriseListSelf.push({
                                enterpriseName:context.enterpriseName,
                                enterpriseId:context.enterpriseId,
                                address:context.address});
                        });
                        this.setState({
                            enterpriseList : enterpriseListSelf,
                        });
                    }
                }
            }
        )
    }
    /*选择联系人*/
    selectContacts(uid){
        this.setState({
            relationPartAUserId:uid,
        });
    }
    columns = [
        {
            title: '订单编号',
            dataIndex: 'oid',
            key: 'oid',
            width: 200,
            render: (text, record, index) => {
                if(record.status >= 3 && (this.serviceType==1||this.serviceType==3) && record.orderType != '1'){
                    return  (
                        <span title={record.oid} className="order_orderpurch_item_from_td_oid_otyp1" onClick={this.jumpstreamshow.bind(this,record.oid)}>{record.oid}</span>
                    )
                }else {
                    return(
                        <span title={record.oid} className="order_orderpurch_item_from_td_oid">{record.oid}</span>
                    )
                }
                /* return  record.orderType ==1?
                 <span title={record.oid} className="order_orderpurch_item_from_td_oid_otyp1" onClick={this.jumpTree.bind(this,record.oid)}>{record.oid}</span>
                 :
                 <span title={record.oid} className="order_orderpurch_item_from_td_oid">{record.oid}</span>*/
            },
        },
        {
            title: '款号',
            dataIndex: 'orderGoodsStyleNos',
            key: 'orderGoodsStyleNos',
            render:(text, record, index) =>{
                return text && text.length > 8 ? (
                    <Tooltip
                        placement="top"
                        title={text}
                        // getPopupContainer={() => document.getElementsByClassName("order_inoutDetailModal")[0]}
                    >
                        <span className='order_detail_remark'>{text}</span>
                    </Tooltip>
                ) : <span>{text}</span>
            }
        },
        {
            title: '采购方',
            dataIndex: 'partAName',
            key: 'partAName',
            width: 260,
            render:(text, record, index) =>{
                return <span title={record.partAName == null ? record.traderName : record.partAName} className="">
                    {
                        record.partAName == null ?
                            <span>{record.traderName} {record.traderName != '' && record.traderName != null ? <a style={{color:'red',cursor:'initial'}}>(未关联)</a> : null}</span>
                            : record.partAName}
                    </span>
            }
        },
        {
            title: '商品类型',
            dataIndex: 'orderType',
            key: 'orderType',
            render:(text, record, index) =>{
                return <span className="">{this.goodtypeobj[record.orderType]}</span>
            }
        },
        {
            title: '数量',
            dataIndex: 'orderGoodsNum',
            key: 'orderGoodsNum',
            render:(text, record, index) =>{
                return <span className="">{Number(record.orderGoodsNum).toFixed(3)}</span>
            }
        },
        {
            title: '剩余数量',
            dataIndex: 'remainOrderGoodsNum',
            key: 'remainOrderGoodsNum',
            render:(text, record, index) =>{
                return <span className="">{Number(record.orderGoodsNum-record.remainOrderGoodsNum).toFixed(3)}</span>
            }
        },
        {
            title: '订单金额（元）',
            dataIndex: 'account',
            key: 'account',
            render:(text, record, index) =>{
                return <span className="">{record.account/100}</span>
            }
        },
        {
            title: '收款金额（元）',
            dataIndex: 'payAccount',
            key: 'payAccount',
            render:(text, record, index) =>{
                return <span className="">{record.payAccount/100}</span>
            }
        },
        {
            title: '订单状态',
            dataIndex: 'status',
            key: 'status',
            render:(text, record, index) =>{
                return <span className="">{this.odsobj[record.status]}</span>
            }
        },
        {
            title: '操作',
            dataIndex: 'operate',
            key: 'operate',
            width: 100,
            render:(text, record, index) =>{
                let _this = this;
                const fun = {
                    jumpDetail:()=>{
                        hashHistory.push({pathname:'/OrderIndex/',state:{
                            'record':record,
                            "defaultActiveKey":1,
                        }})
                    },
                    jumpDeliver:()=>{
                        const r = this.refs;
                        // // 请求数据

                        //显示弹框
                        if(r && r.outModal) { r.outModal.setState({vis:true})}else{ return; }

                        this.inoutHttpRequest(record.oid,(data)=>{
                            // // 显示弹框
                            r.outModal.curOrderId = record.oid;

                            data.forEach((item,index)=>{
                                const d =  data[index]
                                for(let i in d){
                                    d[i] = d[i] != null ? d[i] : "-";
                                }
                            });

                            r.outModal.setState({
                                data:data
                            })
                        });

                    },
                    jumpChain:()=>{
                        hashHistory.push({pathname:'/ordertree/',state:{
                            'oid':record.oid,
                        }})
                    },
                    jumpComplete:()=>{
                        /*Modal.confirm({
                         title: '确定完成本次交易吗?',
                         content: '',
                         onOk() {
                         _this._DealFinished(record.oid);
                         },
                         onCancel() {
                         // console.log('Cancel');
                         },
                         })*/
                        _this._DealFinished(record.oid);
                    },
                    jumpRelation:()=>{
                        _this.setState({
                            relationModalFlag:true,
                            relationOid:record.oid,
                        },_this.selectSearch);

                    },
                    jumpMaterial:()=>{
                        hashHistory.push({pathname:'/OrderIndex/',state:{
                            'record':record,
                            "defaultActiveKey":9,
                        }})
                    },
                    jumpDayang:()=>{
                        Relay.Store.commitUpdate(
                            new findSampleCreateByOrderId({
                                orderId:record.oid
                            }),
                            {
                                onFailure: (e) => {
                                    console.log(e);
                                },
                                onSuccess: (res) => {
                                    res = res.findSampleCreateByOrderId.responseData;

                                    if(res.errorCode === "0" && res.sampleCreate === null){
                                        hashHistory.push({pathname:'/createproofing',state:{
                                            'record':record
                                        }})
                                    }else{
                                        hashHistory.push({pathname:'/OrderIndex',state:{
                                            'record':record,
                                             defaultActiveKey: 10,
                                             showProofing:1
                                        }})
                                    }
                                }
                            }
                        );
                    }
                };
                const menuItem = [
                    {key:"detail",iconType:"file-text",text:"查看详情",onClick:()=>{fun.jumpDetail();}},
                    {key:"dayang",iconType:"bars",text:"打样管理",onClick:()=>{fun.jumpDayang();}},
                    {key:"deliver",iconType:"export",text:"发货",onClick:()=>{fun.jumpDeliver();}},
                    {key:"complete",iconType:"check-circle-o",text:"完成交易",onClick:()=>{fun.jumpComplete();}},
                    {key:"relation",iconType:"usb",text:"关联贸易商",onClick:()=>{fun.jumpRelation();}},
                    {key:"chain",iconType:"share-alt",text:"查看供应链",onClick:()=>{fun.jumpChain();}},
                    {key:"material",iconType:"plus-square-o",text:"添加物料清单",onClick:()=>{fun.jumpMaterial();}},
                ];

                const menu = (
                    <Menu
                        className="listOrder_purchase_dropDown_menu"
                    >
                        {
                            menuItem.map((v,i)=>{
                                if(this.serviceType == 1 && record.orderClassify == 1){
                                    //制衣厂--录入的成衣订单
                                    if(record.status == 3 ){//已签订
                                        if(v.key == "complete"||v.key == "detail"||v.key == "material"){
                                            return (
                                                <Menu.Item key={v.key}>
                                                    <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                </Menu.Item>
                                            )
                                        }else if(v.key == "dayang"){//只有成衣订单可见-已签订
                                            if(record.orderType == 1){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}
                                                        ><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }
                                    }else if(record.status == 4 ){//交易完成
                                        if(record.partAName){
                                            if(v.key == "detail"){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }else {
                                            if(v.key == "relation"||v.key == "detail"){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }
                                    }
                                }else {
                                    //正常-贸易商发布的成衣订单 或 制衣厂新建的成衣订单
                                    if(record.status == 3 ){//已签订
                                        if(v.key == "chain"){//查看供应链
                                            if(this.serviceType == 6 ||this.serviceType == 1){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }else if(v.key == "material"){//只有制衣厂可见-交易完成隐藏按钮
                                            if(this.serviceType == 1){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}
                                                        ><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }else if(v.key == "deliver"||v.key == "detail"){
                                            return (
                                                <Menu.Item key={v.key}>
                                                    <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                </Menu.Item>
                                            )
                                        }else if(v.key == "dayang"){//只有成衣订单可见-已签订
                                            if(record.orderType == 1){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}
                                                        ><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }
                                    }else if(record.status == 4 ){//交易完成
                                        if(v.key == "chain"){
                                            {/*查看供应链*/}
                                            if(this.serviceType == 6 ||this.serviceType == 1){
                                                return (
                                                    <Menu.Item key={v.key}>
                                                        <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                    </Menu.Item>
                                                )
                                            }
                                        }else if(v.key == "detail"){
                                            {/*详情*/}
                                            return (
                                                <Menu.Item key={v.key}>
                                                    <span className="listOrder_purchase_dropDown_menuItem" onClick={v.onClick}><Icon type={v.iconType} className="listOrder_purchase_dropDown_menuItem_icon"/>{v.text}</span>
                                                </Menu.Item>
                                            )
                                        }
                                    }
                                }
                            })
                        }
                    </Menu>
                );
                return (
                    <Dropdown overlay={menu} placement="bottomLeft">
                        <Icon type="ellipsis" className="listOrder_purchase_dropDown_icon"/>
                    </Dropdown>
                )
            }
        },
    ];

    render(){
        let { orders,outDetailModalInfo,enterpriseList,linkman,linkKey,tradeKey } = this.state;
        return (
            <div className="order_box">
                <div className="order_saleandre_frome_search_box">
                    <div style={{display:"flex",alignItems:"center",marginLeft:'20px',marginRight: '-3px'}}>
                        款号：
                        <InputBox className="order_saleandre_frome_search_input pro_overflow_inputSty "
                                  space={20}
                                  ref={"styleNo"}
                                  defaultvalute="请输入款号"
                                  changeon={this.bluronInput.bind(this,"styleNo")}
                        />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        采购方：
                        <InputBox className="order_saleandre_frome_search_input pro_overflow_inputSty "
                                  space={20}
                                  ref={"enName"}
                                  defaultvalute="请输入企业名称"
                                  changeon={this.bluronInput.bind(this,"enName")}
                        />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <Button onClick={this._SearchByEn.bind(this)}>搜索</Button>
                    </div>

                    {/*<div className="order_saleandre_frome_search_div" onClick={this._SearchByEn.bind(this)}>搜索</div>*/}
                </div>

                <div style={{height:"300px",background:"#fff",margin:"20px"}}>
                    {/*修改-0602*/}
                    <Table
                        columns={this.columns}
                        dataSource={orders}
                        className="order_table"
                        pagination={false}
                        rowKey={record => record.oid}
                        loading={this.state.loading}
                    />
                    <Modal className="order_creat_batchhint_modal"
                           title="关联贸易商"
                           visible={this.state.relationModalFlag}
                           onCancel={this.handleCancel.bind(this)}
                           onOk={this.handleOk.bind(this)}
                    >
                        <p className="order_list_sale_hint_text" ref={"enterpriseList"}>
                            <span className="order_list_sale_hint_word">贸易商：</span>
                            <span className="order_list_sale_hint_left">
                                <Select
                                    key={tradeKey}
                                    showSearch
                                    style={{ width: 200 }}
                                    className="order_creat_select"
                                    dropdownClassName="order_creat_select_drop"
                                    placeholder="请输入贸易商名称"
                                    notFoundContent="该企业未入驻平台"
                                    optionFilterProp="children"
                                    getPopupContainer={()=>this.refs.enterpriseList}
                                    defaultActiveFirstOption={false}
                                    showArrow={false}
                                    onSearch={this.selectSearch.bind(this)}
                                    onChange={this.selectChange.bind(this)}
                                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                >
                                {
                                    enterpriseList&&enterpriseList.map((v,i)=>{
                                        return(
                                            <Option key={v.enterpriseId} value={v.enterpriseId}>{v.enterpriseName}</Option>
                                        )
                                    })
                                }
                            </Select>
                            </span>

                        </p>
                        <p className="order_list_sale_hint_textp" ref={"linkman"}>
                            <span className="order_list_sale_hint_word">联系人：</span>
                            <span className="order_list_sale_hint_left">
                                <Select
                                    key={linkKey}
                                    style={{ width: 200 }}
                                    className="order_creat_select"
                                    dropdownClassName="order_creat_select_drop"
                                    placeholder="请选择联系人"
                                    notFoundContent="该企业未指定联系人"
                                    optionFilterProp="children"
                                    getPopupContainer={()=>this.refs.linkman}
                                    defaultActiveFirstOption={false}
                                    onChange={this.selectContacts.bind(this)}
                                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                >
                                {
                                    linkman&&linkman.map((v,i)=>{
                                        return(
                                            <Option key={v.uid} value={v.uid}>{v.text}</Option>
                                        )
                                    })
                                }
                            </Select>
                            </span>

                        </p>
                    </Modal>
                    <Pagination eachSize={10} dataSize={this.state.totalresult} onSure={this.onSure.bind(this)} ref={'pagination'}/>

                    <OutModal
                        ref="outModal"
                    />
                </div>
            </div>
        )
    }
}

class OutModal extends React.Component{
    constructor(props){
        super(props);
        this.state={
            vis:false,   // 显示隐藏
            fileList:[],    // 上传文件列表 （最后发送的fileList 只含有 done 文件）
            token:"",   //上传图片的touken
            data:[],  //table数据
            LogInfoValue:"",  //物流信息
        };

        this.curOrderId = "";   //当前的订单号，默认为空;
        this.accept = ".xlsx,.xls,.docx,.doc,.pdf,.jpg,.gif,.png,.bmp";
        this.qiniuhref = Config.qiuniu;
        this.maxFileLength = 5;

        this.cancelModal = this.cancelModal.bind(this);
        this.beforeUpload = this.beforeUpload.bind(this);
        this.fileChange = this.fileChange.bind(this);
        this.uploadData = this.uploadData.bind(this);
        this.upLoadClick = this.upLoadClick.bind(this);
        this.handleTableSendQuanChange = this.handleTableSendQuanChange.bind(this);   //table 右侧输入框 Change
        this.handleLogInfoChange = this.handleLogInfoChange.bind(this);  //物流信息
        this.onOk = this.onOk.bind(this);
        this.clear = this.clear.bind(this);
    }

    componentWillMount(){
        Relay.Store.commitUpdate(
            new GetQiNiuToken({}), {
                onSuccess: (res) => {
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken;
                        this.setState({
                            token:qiniutoken
                        })
                    }else if(errorCode==500){
                        message.error("服务器错误，请联系管理员")
                    }
                },
                onFailure:()=>{
                    message.error("网络请求失败 ")
                }
            }
        );
    }

    cancelModal(){
        this.clear();
        const d = this.state.fileList,a = [];
        d.forEach((item,index)=>{
            a.push(item.response.key);
        });

        this.picRemoveHttp(a.join(","))
    }

    columns = [{
        title: '款号',
        dataIndex: 'styleNo',
        key: 'styleNo',
    }, {
        title: '品名',
        dataIndex: 'productName',
        key: 'productName',
    },{
        title: '数量',
        dataIndex: 'quantity',
        key: 'quantity',
        render:(text, record, index) =>{
            return <span className="">{Number(record.quantity).toFixed(3)}</span>
        }
    },{
        title: '剩余数量',
        dataIndex: 'remainingQuantity',
        key: 'remainingQuantity',
        render:(text, record, index) =>{
            return <span className="">{Number(record.remainingQuantity).toFixed(3)}</span>
        }
    },{
        title: '本次发货数量',
        dataIndex: 'sendQuantity',
        key: 'sendQuantity',
        render:(r,t,i)=> <div className="order_inoutDetailModal_sendQuantity_input">
            <InputNumber max="1000000000" min="1" step="5" onChange={(e)=>this.handleTableSendQuanChange(e,i)}
                         value={this.state.data[i].sendRemain}
            />
        </div>
    }];

    handleTableSendQuanChange(e,i){

        if(!e) {
            this.state.data[i].sendRemain = undefined;
            this.setState({
                data:this.state.data
            });
            return;
        }

        e = e.toString();

        const maxLength = 3,
            num = (e.length-1) - e.indexOf(".");

        if( e.indexOf(".")!= -1 && num > maxLength){
            return
        }

        this.state.data[i].sendRemain = e;

        this.setState({
            data:this.state.data
        })
    }


    beforeUpload(file){
        const MaxSize = 10;  //最大限度 10M;
        let Reg = [".xlsx",".xls",".docx",".doc",".pdf", ".jpg", ".gif","png","bmp"];  //格式

        function formatTest(reg,name){
            if(!reg || !name){ return; }
            const D = Array.from(reg),
                N = name.toLowerCase();
            for(let i in D){
                const I = D[i].toLowerCase();
                if(N.lastIndexOf(I) !== -1){
                    return true
                }
            }
            return false;
        }
        if(!!file.name){
            if(!formatTest(Reg,file.name)) {
                message.error("文件格式错误，请重新选择");
                return false;
            }
        }

        // 图片大小
        if( file.size / 1024 / 1024 > MaxSize ){
            message.error("图片大小超过限制");
            return false;
        }
    }

    ImgTestPromise(base64){
        return new Promise(function (reslove,reject) {
            let Img = new Image();
            Img.src = base64;
            Img.onload = function(){
                if(  Img.width !== 0 && Img.height !== 0){
                    reslove();
                }else{
                    reject();
                }
            };
            Img.onerror = function () {   reject(); }
        })
    }

    FileBase64(img,callback){
        const f = new FileReader();
        f.addEventListener("load",function(){
            callback(this.result);
        });
        f.readAsDataURL(img)
    }

    uploadPlugin = {
        action:"http://up-z2.qiniu.com",
        beforeUpload:this.beforeUpload,
        accept:this.accept
    };

    uploadData(file){
        const token = this.state.token;
        if(!token) { message.error("上传参数错误"); return;}
        const date = new Date().getTime();
        return {file:file,token:this.state.token,key:`moneyInfo_${date}`}
    }

    fileChange({file,fileList}){

        // 先更新临时文件列表
        this.setState({fileList:fileList});

        if(file.status === "done"){
            let f = fileList[fileList.length-1];

            f.url = this.qiniuhref + f.response.key + `?attname=${f.name}`;

            // 过滤name如果是空的话，那么就添加一个默认名称
            if(f.name.lastIndexOf(".") == "0" ){ f.name = "1"+f.name }

            // 如果是图片就验证图片格式
            if(f.type.slice(0, f.type.indexOf("/")) == "image"){
                this.FileBase64(file.originFileObj,(base64)=>{
                    this.ImgTestPromise(base64).then(()=>{
                        //成功时，把所有的list复制到filelist里
                        this.setState({fileList:fileList});
                    }).catch((err)=>{
                        let f = this.state.fileList;
                        f.length = f.length-1;  // 删除最后一个
                        message.error("当前图片格式错误，请检查图片格式");
                        this.setState({fileList:f})
                    });
                });
            }
        }else if(file.status == "error"){
            message.error(file.error);
        }else if(file.status == "removed"){
            this.picRemoveHttp(file.response.key);
        }
    }

    upLoadClick(){
        if(this.state.fileList.length >= this.maxFileLength) {
            message.info(`最多只可上传${this.maxFileLength}个附件`);
        }
    }

    handleLogInfoChange(e){
        this.setState({
            LogInfoValue:e.target.value
        })
    }

    textRegTest(text){
        let r = /[^ ]/;
        return r.test(text);
    }

    picRemoveHttp(str){
        Relay.Store.commitUpdate(
            new DelQiniuFileMutation({
                fileKey: str
            }),
            {
                onFailure: () => {
                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if (errorCode == 0) {
                    }
                }
            }
        )
    }

    clear(){
        this.setState({
            fileList:[],
            data:[],  //table数据
            LogInfoValue:"",  //物流信息
            vis:false,
        })
    }

    onOk(){
        // 把本地时间转换为时间戳
        let d = this.state.data,
            l = this.state.LogInfoValue,
            f = this.state.fileList,
            num = 0 ,

            d_arr = [],f_arr = [];

        // 格式验证asd
        if(!this.textRegTest(l)){
            message.error("请填写物流信息");
            return;
        }

        // 验证是否有orderId
        if(!this.curOrderId){ return; message.error("数据出错，请联系系统管理员"); }

        for(let i =0; i<f.length; i++){
            if(f[i].status === "done"){
                f_arr.push(f[i]);
            }else{
                message.error("请等待文件上传完毕");
                return;
            }
        }

        // 时间格式转换  and  筛选只有本次发货数量的才发送（后台强制要求）
        // [sendRemain]为自定义的输入数量，[sendQuantity]为需要发送的字段
        d.forEach((item)=>{
            if(item.sendRemain){
                ++num;  //用于计算本次发货数量是否全部为空
                item.createDate = new Date().getTime();

                // 设置 goodsName 因为收发货使用的是这个字段. 把多余字段 [productName]删除
                item.goodsName = item.productName;
                delete item.productName;

                //改掉 sendQuantity
                item.sendQuantity = item.sendRemain;

                d_arr.push(item);
            }
        });

        //发货数量全部为空
        if(num <= 0 ){ message.info("请至少输入一个发货数量"); return; }

        Relay.Store.commitUpdate(
            new SendGoodsOrderMutation({
                uid:sessionStorage.getItem("uid"),
                orderId:this.curOrderId,
                logisticsMsg:l,
                url1:JSON.stringify(f_arr),
                goodsInfo:JSON.stringify(d_arr),
            }), {
                onSuccess: (res) => {
                    const d = res.sendGoodsOrder.sendGoodsOrder;
                    if(d.errorCode == "0"){
                        message.success("发货成功");
                        this.clear();
                    }else{
                        if(d.errorCode == "500"){
                            message.error("服务器错误，请联系系统管理员");
                        }
                    }
                },
                onFailure:()=>{
                    message.error("网络请求失败 ")
                }
            }
        );
    }

    render(){
        const {vis,fileList,data,LogInfoValue} = this.state;

        return <Modal
            title="发货"
            style={{width:1000}}
            className="order_inoutDetailModal"
            visible={vis}
            onOk={this.onOk}
            onCancel={this.cancelModal}
        >
            <h3 className="order_inoutDetailModal_title">
                填写发货明细：
            </h3>

            <Table
                className="order_tableModalOverflow"
                columns={this.columns}
                dataSource={data}
                pagination={false}
            />

            <div className="order_inoutDetailModal_loginfo">
                <h3 className="order_inoutDetailModal_title">
                    物流信息：
                </h3>
                <Input type="textarea" rows={4} placeholder="请输入物流信息" maxLength="1000" onChange={ this.handleLogInfoChange }
                       value={LogInfoValue} style={{boxSizing:"border-box",width:'100%'}}
                />
            </div>

            <div className="order_inoutDetailModal_upFile">
                <h3 className="order_inoutDetailModal_title _left">
                    附件：
                </h3>
                {
                    <Upload
                        className="order_out_record_fileList"
                        fileList={fileList}
                        {...this.uploadPlugin}
                        data={this.uploadData}
                        onChange={this.fileChange}
                        disabled={fileList.length >= this.maxFileLength &&  true}
                    >
                        <button className="order_inout_record_btn" onClick={this.upLoadClick}>
                            上传
                        </button>
                    </Upload>
                }
                {
                    <p className="operLog_auditAlarm">
                        请上传10M以内的excel、word、pdf、jpg、gif、png、bmp格式的文件
                    </p>
                }
            </div>
        </Modal>
    }
}
